import pygame
import os

import random

from eventType import *
from bullet import Bullet
from settings import REFRESH_FPS

class Enemy(pygame.sprite.Sprite):
    def __init__(self, filename, blood, angle, scale, level ,screen, avm):
        pygame.sprite.Sprite.__init__(self)

        self.screen = screen
        self.filename = filename
        self.angle = angle,
        self.scale = scale
        self.avm = avm
        # 表示敌机的等级
        self.level = level
        self.image = pygame.image.load(filename)
        self.image = pygame.transform.rotozoom(self.image, angle, scale)

        self.rect = self.image.get_rect()
        
        self.rect.x = random.randint(0, screen.get_width() - self.rect.width)
        
        # 血量
        self.blood = blood
        # 子弹集合
        self.bullets = pygame.sprite.Group()
        
        self.screen = screen

        self.bCount = 0
        self.dead_action = 0


    def display(self):
        self.screen.blit(self.image, self.rect)
    
    def update(self):
        # 敌机移动
        self.rect.y += 1
        if self.rect.y >= self.screen.get_height():
            self.kill()
            return
        
        # 创建敌机子弹
        self.bCount += 1
        # 每1/2秒(500ms)创建一次子弹
        if self.bCount == REFRESH_FPS / 2:
            bullet_image_name = 'bullet1' if self.level == 1 else 'bullet2'
            bullet_image_angle = 180 if self.level == 1 else -135
            bullet_image_size = 20 if self.level == 1 else 30
            bullet_strength = 1 if self.level == 1 else 2
            bullet_blood = 1 if self.level == 1 else 2
            bullet_speed = 8
            self.bullets.add(Bullet('images/'+ bullet_image_name +'.png', bullet_strength, bullet_blood, bullet_speed, bullet_image_angle,bullet_image_size,self.screen, self, False))
            self.bCount = 0

        # 更新子弹状态
        for bul in self.bullets:
            bul.update()
        
        if self.blood <= 0:
            if self.dead_action >= REFRESH_FPS / 2:
                self.kill()
                self.avm.update(self.filename)
                return
            self.displayDead()
            self.dead_action += 1
            return
        
        self.display()
    
    def displayDead(self):
        if self.dead_action == 0:
            self.image = pygame.image.load(os.path.join('images', 'enemy_dead.png'))
            self.image = pygame.transform.rotozoom(self.image, 0, 0.16)
        elif self.dead_action == REFRESH_FPS / 3:
            self.image = pygame.transform.rotozoom(self.image, 0, 0.22)
        
        self.display()
